<template>
    <el-form ref="registerFrom" :model="registerFrom" label-width="auto" label-position="top" size="large" class="my-form"
        :rules="rules">
        <el-text type="primary" size="large">
            <h1 class="my-h1">注册账号</h1>
        </el-text>
        <el-row>
            <el-link @click="toLogin" type="primary" style="margin-left: 65%;">已有账号？返回登录</el-link>
        </el-row>
        <el-form-item label="用户名" prop="username">
            <el-input v-model="registerFrom.username" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
            <el-input type="password" v-model="registerFrom.password" show-password />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
            <el-input v-model="registerFrom.email" />
        </el-form-item>
        <el-form-item label="联系电话" prop="phone">
            <el-input v-model="registerFrom.phone" />
        </el-form-item>
        <el-form-item label="验证码" prop="code">
            <el-input v-model="registerFrom.code" />
        </el-form-item>
        <el-form-item style="align-content: center;">
            <el-button @click="sendCode">发送验证码</el-button>
            <el-button type="primary" @click="onSubmit()">注册</el-button>
            <el-button @click="resetForm()">重置</el-button>
        </el-form-item>
    </el-form>
</template>

<script>
import axios from 'axios';
import { ElMessage } from 'element-plus';
import { MD5 } from 'crypto-js';

axios.defaults.baseURL = '/api';

export default {
    data() {
        return {
            codeMd5: '-----',
            registerFrom: {
                username: '',
                password: '',
                email: '',
                phone: '',
                code: '',
            },
            rules: {
                username: [
                    { required: true, message: '请输入用户名', trigger: 'blur' }
                ],
                email: [
                    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
                    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
                ],
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { min: 6, max: 15, message: '密码长度在 6 到 15 个字符之间', trigger: 'blur' }
                ],
                phone: [
                    { required: true, message: '请输入电话号码', trigger: 'blur' },
                    { pattern: /^1\d{10}$/,  message: '请输入正确的电话号码', trigger: 'blur' }
                ],
                code: [
                    { required: true, message: '请输入验证码', trigger: 'change' }
                ]
            }
        };
    },
    methods: {
        resetForm() {
            this.registerFrom.username = '';
            this.registerFrom.password = '';
            this.registerFrom.email = '';
            this.registerFrom.phone = '';
        },
        onSubmit() {
            this.$refs.registerFrom.validate((valid) => {
                if (valid) {
                    if (this.codeMd5 === '-----') {
                        ElMessage.info("请向服务端发送验证码");
                        return;
                    }
                    if (MD5(this.registerFrom.code).toString() !== this.codeMd5) {
                        ElMessage.error("验证码错误");
                        return;
                    }
                    const data = {
                        username: this.registerFrom.username,
                        email: this.registerFrom.email,
                        password: MD5(this.registerFrom.password).toString(),
                        phone: this.registerFrom.phone,
                    }
                    axios.post('/register', data)
                        .then((result) => {
                            if (result.data.code === 1) {
                                ElMessage.success("注册成功");
                                this.$cookies.set('token', result.data.data);
                                this.$store.state.isLogin = true;
                                this.$store.state.navActive = '/home';
                            } else {
                                console.log(result.data);
                                if (result.data.msg === "username_exist") {
                                    ElMessage.info("用户名 " + this.registerFrom.username + " 已被占用");
                                    return;
                                }
                                ElMessage.error("注册失败！！！");
                            }
                        })
                        .catch(err => {
                            console.log(err);
                            if (err.response.status === 500) {
                                ElMessage.error("无法连接后端服务器");
                                return;
                            }
                            ElMessage.error("注册失败！！！");
                        })
                } else {
                    ElMessage.info(" 有字段不符合要求 ");
                    return false;
                }
            });
        },
        toLogin() {
            this.$store.state.navActive = '/login';
        },
        sendCode() {
            this.$refs.registerFrom.validateField('email', (valid) => {
                if (valid) {
                    axios.get('/sendMail/' + this.registerFrom.email)
                        .then(result => {
                            if (result.data.code === 1) {
                                this.codeMd5 = result.data.data;
                                ElMessage.success("验证码已发送到指定邮箱");
                                setTimeout(() => this.codeMd5 = '-----',1000 * 60 * 3);
                            } else {
                                console.log(result.data);
                                ElMessage.error("验证码发送失败！！！");
                            }
                        })
                        .catch(err => {
                            console.log(err);
                            if (err.response.status === 500) {
                                ElMessage.error("无法连接后端服务器");
                                return;
                            }
                            ElMessage.error("验证码发送失败！！！");
                        })
                }
            })

        }
    }
}
</script>

<style>
.my-h1 {
    color: #000;
    text-align: center;
    font-size: 28px;
}

.my-form {
    width: 50%;
    max-width: 400px;
    margin: 0 auto;
}
</style>